<template>
    <div class="Kpicture">
        <div class="pictureClassfiy">
            <div @click="ChangePicture(1)" :class="showKPicture === 1 ? 'active-border' : 'normal-border'">日K线</div>
            <div @click="ChangePicture(2)" :class="showKPicture === 2 ? 'active-border' : 'normal-border'">周K线</div>
            <div @click="ChangePicture(3)" :class="showKPicture === 3 ? 'active-border' : 'normal-border'">月K线</div>
        </div>
        <div class="Picture">
            <div ref="chartDom" class="PictureContent"></div>
            <div class="AITalk">
                <div class="chat-box">
                    <div class="chat-header">
                        AI Chat
                    </div>
                    <div class="chat-content" style="height: 500px; overflow-y: auto; padding: 10px;">
                        <div v-for="(message, index) in messages" :key="index" class="message"
                            :class="{ 'user-message': message.isUser, 'ai-message': !message.isUser }">
                            <div class="message-content">{{ message.text }}</div>
                        </div>
                    </div>
                    <div class="chat-input">
                        <el-input v-model="inputMessage" :rows="3" type="textarea" placeholder="Please input"
                            style="width: 85%;" />
                        <el-button class="sub" @click="sendMessage" type="primary">发送</el-button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref } from 'vue'
import * as echarts from 'echarts';
import { getKlineDataApi } from '@/api/tushare';

let showKPicture = ref(1)

const props = defineProps({
    introObj: {
        type: Object,
        required: true
    }
});



function ChangePicture(index) {
    showKPicture.value = index
    getKData()
}
const chartDom = ref(null)


onMounted(() => {
    getKData()
})

const draw = (chartDom,rawData)=>{
    const myChart = echarts.init(chartDom);
    let option;

    const upColor = '#ec0000';
    const upBorderColor = '#8A0000';
    const downColor = '#00da3c';
    const downBorderColor = '#008F28';
    // Each item: open，close，lowest，highest
    const data0 = splitData(rawData);
    function splitData(rawData) {
        const categoryData = [];
        const values = [];
        for (let i = 0; i < rawData.length; i++) {
            categoryData.push(rawData[i].splice(0, 1)[0]);
            values.push(rawData[i]);
        }
        return {
            categoryData: categoryData,
            values: values
        };
    }
    function calculateMA(dayCount) {
        const result = [];
        let i = 0, len = data0.values.length;
        for (; i < len; i++) {
            if (i < dayCount) {
                result.push('-');
                continue;
            }
            let sum = 0;
            for (let j = 0; j < dayCount; j++) {
                sum += +data0.values[i - j][1];
            }
            result.push(sum / dayCount);
        }
        return result;
    }
    option = {
        title: {
            text: '',
            left: 0
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross'
            }
        },
        legend: {
            data: ['K线', 'MA5', 'MA10', 'MA20', 'MA30']
        },
        grid: {
            left: '10%',
            right: '10%',
            bottom: '15%'
        },
        xAxis: {
            type: 'category',
            data: data0.categoryData,
            boundaryGap: false,
            axisLine: { onZero: false },
            splitLine: { show: false },
            min: 'dataMin',
            max: 'dataMax'
        },
        yAxis: {
            scale: true,
            splitArea: {
                show: true
            }
        },
        dataZoom: [
            {
                type: 'inside',
                start: 0,
                end: 100
            },
            {
                show: true,
                type: 'slider',
                top: '90%',
                start: 0,
                end: 100
            }
        ],
        series: [
            {
                name: 'K线',
                type: 'candlestick',
                data: data0.values,
                itemStyle: {
                    color: upColor,
                    color0: downColor,
                    borderColor: upBorderColor,
                    borderColor0: downBorderColor
                },
                markPoint: {
                    label: {
                        formatter: function (param) {
                            return param != null ? Math.round(param.value) + '' : '';
                        }
                    },
                    data: [
                        {
                            name: 'Mark',
                            coord: ['2013/5/31', 2300],
                            value: 2300,
                            itemStyle: {
                                color: 'rgb(41,60,85)'
                            }
                        },
                        {
                            name: 'highest value',
                            type: 'max',
                            valueDim: 'highest'
                        },
                        {
                            name: 'lowest value',
                            type: 'min',
                            valueDim: 'lowest'
                        },
                        {
                            name: 'average value on close',
                            type: 'average',
                            valueDim: 'close'
                        }
                    ],
                    tooltip: {
                        formatter: function (param) {
                            return param.name + '<br>' + (param.data.coord || '');
                        }
                    }
                },
                markLine: {
                    symbol: ['none', 'none'],
                    data: [
                        [
                            {
                                name: 'from lowest to highest',
                                type: 'min',
                                valueDim: 'lowest',
                                symbol: 'circle',
                                symbolSize: 10,
                                label: {
                                    show: false
                                },
                                emphasis: {
                                    label: {
                                        show: false
                                    }
                                }
                            },
                            {
                                type: 'max',
                                valueDim: 'highest',
                                symbol: 'circle',
                                symbolSize: 10,
                                label: {
                                    show: false
                                },
                                emphasis: {
                                    label: {
                                        show: false
                                    }
                                }
                            }
                        ],
                        {
                            name: 'min line on close',
                            type: 'min',
                            valueDim: 'close'
                        },
                        {
                            name: 'max line on close',
                            type: 'max',
                            valueDim: 'close'
                        }
                    ]
                }
            },
            {
                name: 'MA5',
                type: 'line',
                data: calculateMA(5),
                smooth: true,
                lineStyle: {
                    opacity: 0.5
                }
            },
            {
                name: 'MA10',
                type: 'line',
                data: calculateMA(10),
                smooth: true,
                lineStyle: {
                    opacity: 0.5
                }
            },
            {
                name: 'MA20',
                type: 'line',
                data: calculateMA(20),
                smooth: true,
                lineStyle: {
                    opacity: 0.5
                }
            },
            {
                name: 'MA30',
                type: 'line',
                data: calculateMA(30),
                smooth: true,
                lineStyle: {
                    opacity: 0.5
                }
            }
        ]
    };

    option && myChart.setOption(option);
}


const messages = ref([
    { text: "你好，我是你的AI助手。", isUser: false }
]);
const inputMessage = ref('');

const sendMessage = () => {
    if (inputMessage.value) {
        messages.value.push({ text: inputMessage.value, isUser: true });
        // 这里可以添加逻辑，将消息发送给AI并接收回复，暂时模拟回复
        setTimeout(() => {
            messages.value.push({ text: "收到你的消息：" + inputMessage.value, isUser: false });
            inputMessage.value = '';
        }, 1000);
    }
};

const getKData = ()=>{
    const kData = []
    getKlineDataApi(showKPicture.value, props.introObj.ts_code).then(res=>{
        // h获取每个所需字段的所有索引
        let needItem = ["trade_date","open", "close", "low", "high"]
        let indexList = []
        let fileds = res.fields
        for(let i = 0;i < needItem.length;i++){
            let index = fileds.indexOf(needItem[i])
            indexList.push(index)
        }
        // 获取每个所需字段的所有数据
        for(let i = 0;i < res.items.length;i++){
            let item = []
            let dateIndex = indexList[0]
            let date = res.items[i][dateIndex]
            item.push(formatDate(date))
            for(let j = 1;j < indexList.length;j++){
                item.push(res.items[i][indexList[j]])
            }
            kData.push(item)
        }
        // console.log(kData);
        
        draw(chartDom.value,kData)
    })
}

function formatDate(dateString) {
    // 提取年、月、日
    let year = dateString.slice(0, 4);
    let month = dateString.slice(4, 6);
    let day = dateString.slice(6, 8);
    // 去除多余的 0
    month = parseInt(month);
    day = parseInt(day);
    // 拼接并添加分隔符
    return `${year}/${month}/${day}`;
}

</script>

<style scoped>
.Kpicture {
    background: white;
    width: 100%;
    margin-left: 0%;
    padding: 19px;
    border-radius: 52px;
    margin-top: 18px;
}

.pictureClassfiy {
    display: flex;
    border-left: 7px solid #3377ff;
    padding-left: 16px;
    font-size: 16px;
    font-weight: 800;
    margin-bottom: 8px;
}

.pictureClassfiy div {
    margin-left: 5%;
    cursor: pointer;
}

.Picture {
    margin-top: 17px;
    border-top: 1px solid #b3acac;
    display: flex;
}

.active-border {
    border-bottom: 3px solid #3377ff;
}

.normal-border {
    border-bottom: 3px solid white;
}

.PictureContent {
    height: 600px;
    width: 600px;
    margin-top: 10px;
    padding-bottom: 30px;
    padding-left: 50px;
}

.AITalk {}

.chat-box {
    display: flex;
    flex-direction: column;
    font-family: Arial, sans-serif;
    width: 511px;
    height: 594px;
    border: 1px solid rgb(204, 204, 204);
    border-radius: 10px;
    overflow: hidden;
    margin-left: 71px;
    margin-top: 10px;
}

.chat-header {
    text-align: center;
    font-weight: bold;
    background-color: rgb(247 247 247);
    color: #615e5e;
    padding: 10px;
    font-size: 20px;
}

.chat-content {
    flex-grow: 1;
    position: relative;
}

.message {
    margin-bottom: 10px;
}

.user-message {
    width: 80%;
    float: right;
    margin-top: 10px;
}

.ai-message {
    width: 86%;
}

.message-content {
    display: inline-block;
    padding: 5px 10px;
    border-radius: 5px;
    /*background-color: #f0f0f0;*/
}

.user-message .message-content {
    background-color: #f0f0f0;
    margin-bottom: 18px;
    text-align: right;
    float: right;
}

.chat-input {
    display: flex;
    padding: 10px;
    position: relative;
}

.chat-input input {
    outline: none;
}

.sub {
    margin-left: 12px;
    position: absolute;
    right: 14px;
    bottom: 11px;
}
</style>